﻿using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Http.Metadata;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;

namespace CatTalkWeb_Blazor_Ver_.Server.Controllers {
    [Route("api/[controller]")]
    [ApiController]
    public class UpLoadController : ControllerBase {
        [HttpGet]
        public string Get() {
            Response.Headers.ContentEncoding = "utf-8";
            return "哈哈";
        }

        [HttpPost]
        public async Task<IActionResult> PostUrl([FromForm] IFormFile? fileT) {
            Console.WriteLine("接受到了文件上传" + Request.Form.ToString());
            var formFile = Request.Form.Files[0];
            try {
                Dictionary<string, string> dict = new Dictionary<string, string>();
                //foreach (var file in files) {
                var trustedFileNameForFileStorage = Path.GetRandomFileName();
                trustedFileNameForFileStorage += ".png";
                var path = Path.Combine(Environment.CurrentDirectory, "unsafe_uploads", trustedFileNameForFileStorage);//文件路径
                await using FileStream fs = new(path, FileMode.CreateNew);
                await formFile.CopyToAsync(fs);
                dict.Add(trustedFileNameForFileStorage, "api/Upload/image/" + trustedFileNameForFileStorage);
                // }
                return new JsonResult(new {
                    Msg = "",
                    Code = 0,
                    Data = new { SuccMap = dict }
                });
            }
            catch (Exception ex) {
                Console.WriteLine("上传文件失败" + ex.Message);
            }

            return new JsonResult(new {
                Msg = "错误",
                Code = -1000,
                Data = new { }
            });
        }

        [HttpGet("image/{id}")]
        public IActionResult GetImage(string id) {
            var path = Path.Combine(Environment.CurrentDirectory, "unsafe_uploads", id);//文件路径
            if (System.IO.File.Exists(path)) {
                return new PhysicalFileResult(path, "image/png"); //<==Change Media Content Type
            } else {
                return NotFound();
            }
        }
    }
}
